<template>
    <el-dialog title="考勤汇总" :close-on-click-modal="false" :visible.sync="visible" width="60%">
        <div class="train-checkinrecord-box">
            <div>
                <div><span style="font-size: 16px">考勤时间设置：</span></div>
                <div>
                    <div style="margin-top: 10px">
                        <span>上午签到：</span>
                        <el-time-picker arrow-control is-range v-model="amSignInTime" range-separator="-"
                                        start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"/>
                    </div>
                    <div style="margin-top: 10px">
                        <span>上午签退：</span>
                        <el-time-picker arrow-control is-range v-model="amSignOutTime" range-separator="-"
                                        start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"/>
                    </div>
                    <div style="margin-top: 10px">
                        <span>下午签到：</span>
                        <el-time-picker arrow-control is-range v-model="pmSignInTime" range-separator="-"
                                        start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"/>
                    </div>
                    <div style="margin-top: 10px">
                        <span>下午签退：</span>
                        <el-time-picker arrow-control is-range v-model="pmSignOutTime" range-separator="-"
                                        start-placeholder="开始时间" end-placeholder="结束时间"
                                        placeholder="选择时间范围"></el-time-picker>
                    </div>
                </div>
            </div>
            <el-tooltip class="item" effect="dark" content="点击按钮设置或更新考勤时间并生成二维码" placement="top">
                <el-button type="success" icon="el-icon-d-arrow-right" circle @click="setAttrTime"/>
            </el-tooltip>
            <div :class="{'train-checkinrecord-qecode':true,'train-checkinrecord-is-qecode':!qrCodeShow}">
                <vue-qr :text="String(trainId)" :correctLevel="3" :logoScale="0.4" :size="150" :margin="0"
                        :dotScale="1"/>
            </div>
        </div>
        <el-form :inline="true" style="margin-top: 10px">
            <el-form-item>
                <el-date-picker v-model="selectTime" type="datetimerange" range-separator="至"
                                value-format="timestamp" start-placeholder="开始日期"
                                end-placeholder="结束日期"></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button @click="getDataList()">搜索</el-button>
                <el-button type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="dataList" row-key="id" border v-loading="dataListLoading" max-height="400"
                  style="width: 100%;">
            <el-table-column align="center" type="index" header-align="center" width="80" label="序号"/>
            <el-table-column prop="realname" header-align="center" align="center" label="姓名"/>
            <el-table-column prop="deptName" label="部门" header-align="center" align="center"/>
            <el-table-column prop="createTime" label="日期" header-align="center" align="center">
                <template slot-scope="scope">{{scope.row.createTime.slice(0,10)}}</template>
            </el-table-column>
            <el-table-column prop="amSignInStatus" label="上午签到" header-align="center" align="center">
                <template slot-scope="scope">
                    <!--          <span>{{scope.row.amSignInTime?'已签到':'已签退'}}</span>-->
                    <span v-if="parseInt(scope.row.amSignInStatus) === -1">未签到</span>
                    <span v-if="parseInt(scope.row.amSignInStatus) === 0">迟到</span>
                    <span v-if="parseInt(scope.row.amSignInStatus) === 1">已签到</span>
                </template>
            </el-table-column>
            <el-table-column prop="amSignOutStatus" label="上午签退" header-align="center" align="center">
                <template slot-scope="scope">
                    <!--          <span>{{scope.row.amSignOutTime?'已签到':'已签退'}}</span>-->
                    <span v-if="parseInt(scope.row.amSignOutStatus) === -1">未签退</span>
                    <span v-if="parseInt(scope.row.amSignOutStatus) === 0">早退</span>
                    <span v-if="parseInt(scope.row.amSignOutStatus) === 1">已签退</span>
                </template>
            </el-table-column>
            <el-table-column prop="pmSignInStatus" label="下午签到" header-align="center" align="center">
                <template slot-scope="scope">
                    <!--          <span>{{scope.row.pmSignInTime?'已签到':'已签退'}}</span>-->
                    <span v-if="parseInt(scope.row.pmSignInStatus) === -1">未签到</span>
                    <span v-if="parseInt(scope.row.pmSignInStatus) === 0">迟到</span>
                    <span v-if="parseInt(scope.row.pmSignInStatus) === 1">已签到</span>
                </template>
            </el-table-column>
            <el-table-column prop="pmSignOutStatus" label="下午签退" header-align="center" align="center">
                <template slot-scope="scope">
                    <!--          <span>{{scope.row.pmSignOutTime?'已签到':'已签退'}}</span>-->
                    <span v-if="parseInt(scope.row.pmSignOutStatus) === -1">未签退</span>
                    <span v-if="parseInt(scope.row.pmSignOutStatus) === 0">早退</span>
                    <span v-if="parseInt(scope.row.pmSignOutStatus) === 1">已签退</span>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="sizeChangeHandle"
                @current-change="currentChangeHandle"
                :current-page.sync="pageIndex"
                :page-sizes="[5, 10, 15, 20]"
                :page-size="100"
                layout="sizes, prev, pager, next"
                :total="totalPage">
        </el-pagination>
    </el-dialog>
</template>

<script>
  import VueQr from 'vue-qr'

  export default {
    data () {
      return {
        visible: false,
        trainId: '',
        amSignInTime: '',
        amSignOutTime: '',
        pmSignInTime: '',
        pmSignOutTime: '',
        qrCodeShow: false,
        selectTime: [],
        dataList: [],
        dataListLoading: false,
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        disabled: true
      }
    },
    components: {
      VueQr
    },
    methods: {
      // 获取考勤设置信息
      init (id) {
        this.qrCodeShow = false
        this.visible = true
        this.trainId = id
        this.amSignInTime = ''
        this.amSignOutTime = ''
        this.pmSignInTime = ''
        this.pmSignOutTime = ''
        this.selectTime = []
        this.getDataList()
        this.$http({
          url: this.$http.adornUrl('/train/admin/train/getattendancetime'),
          method: 'post',
          data: {
            trainId: this.trainId
          }
        }).then(res => {
          if (res.data.amStartTimeStr || res.data.amSignOutStartTimeStr || res.data.pmStartTimeStr || res.data.pmSignOutStartTimeStr) {
            if (res.data.amStartTimeStr) {
              this.amSignInTime = [
                this.getDate(res.data.amStartTimeStr),
                this.getDate(res.data.amEndTimeStr)
              ]
            }
            if (res.data.amSignOutStartTimeStr) {
              this.amSignOutTime = [
                this.getDate(res.data.amSignOutStartTimeStr),
                this.getDate(res.data.amSignOutEndTimeStr)
              ]
            }
            if (res.data.pmStartTimeStr) {
              this.pmSignInTime = [
                this.getDate(res.data.pmStartTimeStr),
                this.getDate(res.data.pmEndTimeStr)
              ]
            }
            if (res.data.pmSignOutStartTimeStr) {
              this.pmSignOutTime = [
                this.getDate(res.data.pmSignOutStartTimeStr),
                this.getDate(res.data.pmSignOutEndTimeStr)
              ]
            }
            this.qrCodeShow = true
          } else {
            this.qrCodeShow = false
            // this.$message.warning(res.msg);
          }
        })
      },

      // 获取考勤数据列表
      getDataList () {
        this.dataListLoading = true
        this.$http({
          url: this.$http.adornUrl('/train/admin/train/trainattendancestatistics'),
          method: 'post',
          data: {
            trainId: this.trainId,
            endTime: this.selectTime[1],
            startTime: this.selectTime[0],
            page: this.pageIndex,
            limit: this.pageSize
          }
        }).then(res => {
          if (res && res.code === 200) {
            this.dataList = res.data.list
            this.totalPage = res.data.totalCount
            this.pageIndex = res.data.currPage
            this.disabled = false
          } else {
            this.dataList = []
          }
          this.dataListLoading = false
        })
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },

      // 导出考勤数据列表
      handleDownload () {
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['姓名', '部门', '上午签到', '上午签退', '下午签到', '下午签退']
          const filterVal = ['realname', 'deptName', 'amSignInStatus', 'amSignOutStatus', 'pmSignInStatus', 'pmSignOutStatus']
          const data = this.formatJson(filterVal, this.dataList)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '签到统计表 ' + new Date().toLocaleDateString()
          })
        })
      },
      formatJson (filterVal, jsonData) {
        return jsonData.map(x => ({
          'realname': x.realname,
          'deptName': x.deptName,
          'amSignInStatus': x.amSignInStatus === -1 ? '未签到' : x.amSignInStatus === 0 ? '迟到' : '已签到',
          'amSignOutStatus': x.amSignOutStatus === -1 ? '未签到' : x.amSignOutStatus === 0 ? '早退' : '已签到',
          'pmSignInStatus': x.pmSignInStatus === -1 ? '未签到' : x.pmSignInStatus === 0 ? '迟到' : '已签到',
          'pmSignOutStatus': x.pmSignOutStatus === -1 ? '未签到' : x.pmSignOutStatus === 0 ? '早退' : '已签到'
        })).map(v => filterVal.map(j => v[j]))
      },
      dateTime (value) {
        let val =
          value.toLocaleDateString().replace(/\//g, '-') +
          ' ' +
          value.toTimeString().substr(0, 8)
        return val
      },
      // 设置考勤时间
      setAttrTime () {
        if (!this.amSignInTime || !this.amSignOutTime || !this.pmSignInTime || !this.pmSignOutTime) {
          return false
        }
        this.$http({
          url: this.$http.adornUrl('/train/admin/train/setattendancetime'),
          method: 'post',
          data: {
            id: this.trainId,
            amStartTime: this.getTimestamp(this.amSignInTime[0]),
            amEndTime: this.getTimestamp(this.amSignInTime[1]),
            amSignOutStartTime: this.getTimestamp(this.amSignOutTime[0]),
            amSignOutEndTime: this.getTimestamp(this.amSignOutTime[1]),
            pmStartTime: this.getTimestamp(this.pmSignInTime[0]),
            pmEndTime: this.getTimestamp(this.pmSignInTime[1]),
            pmSignOutStartTime: this.getTimestamp(this.pmSignOutTime[0]),
            pmSignOutEndTime: this.getTimestamp(this.pmSignOutTime[1])
          }
        }).then(res => {
          if (res.code === 200) {
            this.$message({
              message: '更新成功',
              type: 'success',
              duration: 1500
              // onClose: () => {
              //     this.getDataList()
              // }
            })
            this.qrCodeShow = true
          } else {
            this.$message.warning(res.msg)
          }
        })
      },

      // 日期转换为时间戳
      getTimestamp (time) {
        return new Date(time).getTime()
      },

      // 时间戳转为日期并截取时间部分
      getDate (value) {
        let year = new Date().getFullYear()
        let month = new Date().getMonth()
        let day = new Date().getDate()
        return year + '-' + (month + 1) + '-' + day + ' ' + value
      }
    }
  }
</script>

<style lang="scss" scoped>
    .train-checkinrecord-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 2px solid #999;
        padding-bottom: 40px
    }

    .train-checkinrecord-qecode {
        width: 200px;
        padding-top: 20px;

        &.train-checkinrecord-is-qecode {
            position: relative;

            &:after {
                content: '请设置考勤时间并生成二维码';
                padding: 60px 20px;
                width: 150px;
                height: 150px;
                position: absolute;
                top: 20px;
                left: 0;
                background: #e9e9eb;
                text-align: center;
                font-size: 10px;
                color: #999;
            }
        }
    }
</style>
